#!/bin/bash

rootpath=$(pwd)

err_exit() {
    echo $1
    exit $2
}

# 符号安装函数
sym_install() {
    local src="$1"
    local dst="$2"
    test -z "$src" && return 1
    test -z "$dst" && return 1
    test -L "$dst" && return 1
    rm "$dst" -rf &> /dev/null
    ln -s "$src" "$dst"
}

# 追加安装函数
append_install() {
    local src="$1"
    local dst="$2"
    test -z "$src" && return 1
    test -z "$dst" && return 1
    grep ". $src" "$dst" &> dev/null     \
                || echo ". $src" >> "$dst"
}

# 覆盖安装函数
cover_install() {
    local src="$1"
    local dst="$2"
    test -z "$src" && return 1
    test -z "$dst" && return 1
    rm "$dst" -rf &> /dev/null
    /bin/cp "$src" "$dst" -rf
}

# 通用安装函数
kyo_install() {
    local name=$1
    local mode=${2-sym}
    test -e "$name" || return 1
    ${mode}_install "$rootpath/$name" ~/."$name"
}

# 添加字体
font_config() {
    test -L /usr/share/fonts/kyo && return 0
    sudo ln -s $rootpath/fonts /usr/share/fonts/kyo
    cd $rootpath/fonts
    sudo mkfontscale
    sudo mkfontdir
    sudo fc-cache
    cd $rootpath
}

# 配置仓库源
apt_config() {
    test -L /etc/apt/sources.list && return
    local dst=/etc/apt/sources.list
    sudo rm $dst -f
    sudo ln -s $rootpath/sources.list $dst
    sudo apt update
}

# 配置bin目录, 因为固定路径，暂时没用
bin_config() {
    grep 'export PATH=' bashrc &> /dev/null  \
            || echo "export PATH=$PATH:$HOME/bin:$rootpath/bin" >> bashrc
}

# 配置网络
net_config() {
    local net=/etc/network/interfaces
    test -L $net && return
    local ifname=$(ifconfig | egrep 'enp' | awk -F':' '{print $1}')
    test -z "$ifname" && err_exit '找不到网卡!'
    cp $rootpath/interfaces.tpl interfaces
    sed -i "s/KYO_DEV/$ifname/" interfaces
    sudo rm $net -f
    sudo ln -s $rootpath/interfaces $net
}

# 配置wifi
wifi_config() {
    local wifi=/etc/NetworkManager/system-connections
    test -L $wifi && return
    sudo rm $wifi -rf
    sudo ln -s $rootpath/wifi $wifi
}

# 配置用户目录
dirs_config() {
    local datadir=${1-/configs/data}
    sym_install $datadir/desktop $HOME/Desktop
    sym_install $datadir/downloads $HOME/Downloads
    sym_install $datadir/pics $HOME/Pictures
    sym_install $datadir/docs $HOME/Documents
    sym_install $datadir/music $HOME/Music
    sym_install $datadir/video $HOME/Videos
    sym_install $datadir/others $HOME/Public
    sym_install $datadir/others $HOME/Templates
    sym_install $rootpath/user-dirs.dirs ~/.config/user-dirs.dirs
    sym_install $rootpath/user-dirs.locale ~/.config/user-dirs.locale
}

#bin_config
font_config
kyo_install bashrc append
kyo_install inputrc
apt_config
kyo_install tmux.conf
kyo_install gitconfig
kyo_install gnupg
kyo_install ssh
kyo_install mozilla
#sym_install $rootpath/user ~/.config/dconf/user
dirs_config
net_config
wifi_config

